<?php
require_once(LIRBARY_DIR."db.php");
define('GET_USER_INFO', "");
class Boast
{
    public function initBoast($userId)
    {
        $dians = $this->newDice();
        $values = array($userId, STATE_WAITING, time(), json_encode($dians));
        $sql = "insert into tbl_boast(userId, userstate, userlastvisit, dianshu) values('" . implode("','", $values) . "')";
        return DbExecutor::getInstance()->insert($sql);
    }
    
    public function join($boastId, $opponentId)
    {
        $sql = "update tbl_boast set  opponentid='" .$opponentId. "', opponentlastvisit = '" . time() . "', opponentstate='" . STATE_WAITING ."' where id = '" . $boastId . "' and opponentid = 0";
        return DbExecutor::getInstance()->exec($sql) > 0;
    }
    
    public function getInfo($id)
    {
        $sql = "select id,userid,opponentid,userstate,opponentstate,userlastvisit,opponentlastvisit,dianshu,userdian,opponentdian, userresult, opponentresult from tbl_boast where id='" . $id . "'";
        return DbExecutor::getInstance()->get($sql);
    }
    
    /*
        *$params =array("name"=>array("op"=>set, "value"=>''));
        *
        *
    */
    public function updateInfo($id, $params)
    {
        $sqls=array();
        foreach($params as $name => $param)
        {
            if($param["op"] == "set")
            {
                $sqls[] = $name . "=" . "'" . $param["value"] . "'";
            }
            else
            {
                $sqls[] = $name . "=" . $name . "+" . "'" . $param["value"]. "'";
            }
        }
        $sql = "update tbl_boast set " . implode(",", $sqls) . " where id='" . $id . "'";
        return DbExecutor::getInstance()->exec($sql);
    }
    
    public function newDice()
    {
        $_1 = rand(0, pow(6, 6));
        $_2 = rand(0, pow(6, 6));
        $dians1 = array();
        $dians2 = array();
        for($i=0; $i<6; ++$i)
        {
            $dians1[]=$_1%6;
            $dians2[]=$_2%6;
            $_1 = intval($_1/6);
            $_2 = intval($_2/6);
        }
        return array($dians1, $dians2);
        //$sql = "update tbl_boast set  dianshu='". $dians ."' where dianshu!=null and dianshu !='' and id='" . $id = "'";
        //return DbExecutor::getInstance()->exec($sql) == 1 ; 
    }
    
}
?>
